import { useEffect, useState } from "react";
import type { UploadFile } from "antd";
import { fileToBuffer } from "./file";
import {
  beforeUpgrade,
  upgrade,
} from "@/api/upgrade.api";
import { ipc } from '@/ipcRenderer'

import { clocker } from "@/utils/utility";
import { message } from "antd";

const stepItem = {
  SELECT: {
    index: 0,
    name: "selectFile",
    title: "选择"
  },
  UPLOAD: {
    index: 1,
    name: "uploadFile",
    title: "上传"
  },

  UPGRADE: {
    index: 2,
    name: "startUpgrade",
    title: "升级"
  },
  SUCESS: {
    index: 3,
    name: "upgradeSuccess",
    title: "升级成功"
  },

};

export function useUpgrade() {
  const [fileState, setFileState] = useState<UploadFile>();
  const [step, setStep] = useState(stepItem.SELECT);
  const [isVisible, setIsVisible] = useState(false);
  const [progress, setProgress] = useState(0);
  const [version, setVersion] = useState();
  const [newVersion, setNewVersion] = useState();

  const chooseFileAction = async (event, modalApi) => {
    if (event.target?.files.length > 0) {
      const file = event.target.files[0];
      setFileState(file);
      setIsVisible(true);
      const fileBuffer = await fileToBuffer(file);
      beforeUpgrade({fileBuffer}).then(({status}) => {
        if(status === 0) {
          setStep(stepItem.UPLOAD)
        }
      })

    }
  };

  function handleProgress(event, progress) {

    console.log("handleProgress",event, progress )
    setProgress(Math.ceil(progress * 100));
  }

//  useEffect(()=> {

//   ipc.on("UPLOAD-PROGRESS", handleProgress);
//  }, [])


  const upgradeAction = () => {
    ipc.on("UPLOAD-PROGRESS", handleProgress);

    upgrade().then(({status}) => {
      if(status === 0) {
        ipc.removeListener("UPLOAD-PROGRESS", handleProgress);

        setTimeout(() => {
          setStep(stepItem.SUCESS)
          setProgress(0);
        }, 300);


      }
    })

  };


  const removeFileAction = () => {
    setFileState(undefined);
    setIsVisible(false);
    setStep(stepItem.SELECT);
  };
  return {
    fileState,
    step,
    isVisible,
    progress,
    chooseFileAction,
    upgradeAction,
    removeFileAction,
  };
}
